package com.shijie.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shijie.domain.entity.Products;
import com.shijie.domain.entity.Talents;
import com.shijie.mapper.ProductsMapper;
import com.shijie.mapper.TalentTrialsMapper;
import com.shijie.domain.entity.TalentTrials;

import javax.annotation.Resource;

import com.shijie.mapper.TalentsMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import com.shijie.core.AbstractService;

/*
 *  @author: smart boy
 *  @date: 2019-01-15
 */
@Service
public class TalentTrialsService extends AbstractService<TalentTrials> {

	@Resource
	private TalentTrialsMapper talentTrialsMapper;

	@Resource
	private ProductsMapper productsMapper;

	@Resource
	private TalentsMapper talentsMapper;

	public void save(TalentTrials talentTrials){
		if(talentTrials.getId() == null){
			talentTrialsMapper.insertSelective(talentTrials);
		}else{
			talentTrialsMapper.updateByPrimaryKey(talentTrials);
		}
	}

	public void saveById(Integer userId, Integer productId) {

		Condition condition = new Condition(Talents.class);
		Example.Criteria c = condition.createCriteria();
		c.andEqualTo("userId", userId);
		List<Talents> list = talentsMapper.selectByCondition(condition);
		if (list != null && list.size() > 0) {
			Talents talent = list.get(0);
			// 用户是达人
			if (talent.getUserType() == 1) {
				// 插入试用数据
				Condition condition2 = new Condition(TalentTrials.class);
				Example.Criteria c2 = condition2.createCriteria();
				c2.andEqualTo("userId", userId);
				c2.andEqualTo("productId", productId);
				List<TalentTrials> listTrials = talentTrialsMapper.selectByCondition(condition2);

				Products product = productsMapper.selectByPrimaryKey(productId);
				if (listTrials != null && listTrials.size() > 0) {
					TalentTrials talentTrials = listTrials.get(0);
					talentTrials.setTitle(product.getTitle());
					talentTrials.setSubTitle(product.getSubTitle());
					talentTrials.setOriPrice(product.getOriPrice());
					talentTrials.setPrice(product.getPrice());
					talentTrialsMapper.updateByPrimaryKey(talentTrials);
				} else {
					TalentTrials talentTrials = new TalentTrials();
					talentTrials.setTalentId(talent.getId());
					talentTrials.setProductId(productId);
					talentTrials.setTitle(product.getTitle());
					talentTrials.setSubTitle(product.getSubTitle());
					talentTrials.setOriPrice(product.getOriPrice());
					talentTrials.setPrice(product.getPrice());
					talentTrialsMapper.insertSelective(talentTrials);
				}
			}
		}


	}

}
